package com.iussoft.demo.ftp;

import com.iussoft.demo.util.ConfigUtil;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 发布ftpserver
 * @author: Hou Dayu
 * @date: Created in 2020/10/27
 */
public class FtpService {

    public void startFtpServer(){
        try {
            System.out.println("发布FTP服务");
            FtpServerFactory serverFactory = new FtpServerFactory();
            ListenerFactory factory = new ListenerFactory();
            //设置监听端口
            factory.setPort(Integer.parseInt(ConfigUtil.getConfigByKey("ftpPort")));
            //替换默认监听
            serverFactory.addListener("default", factory.createListener());

            BaseUser user = new BaseUser();
            user.setName(ConfigUtil.getConfigByKey("ftpUserName"));
            user.setPassword(ConfigUtil.getConfigByKey("ftpUserPwd"));
            user.setHomeDirectory(ConfigUtil.getConfigByKey("ftpPath"));//"D:/test"
            List<Authority> authorities = new ArrayList<Authority>();//可写的权限设置
            authorities.add(new WritePermission());
            user.setAuthorities(authorities);
            serverFactory.getUserManager().save(user);
            FtpServer server = serverFactory.createServer();
            server.start();
        } catch (FtpException e){
            System.out.println("发布ftp服务失败");
            e.printStackTrace();
        }
    }
}
